<template>
  <div class="app-container project-funding-container">
    <el-form v-if="enterpriseId === null"
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="资金名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item size="mini" label="资质类别" prop="qualificationType">
        <el-select
          v-model="queryParams.qualificationType"
          placeholder="请选择资质类别"
          style="width: 150px"
        >
          <el-option
            v-for="dict in dict.type.project_funding_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item size="mini" label="资质级别" prop="level">
        <el-select
          v-model="queryParams.level"
          placeholder="请选择资质级别"
          style="width: 150px"
        >
          <el-option
            v-for="dict in dict.type.project_funding_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="时间">
            <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
              range-separator="-" start-placeholder="发布时间" end-placeholder="有效时间"></el-date-picker>
          </el-form-item> -->
      <!-- <el-form-item label="时间" prop="releaseDate">
            <el-date-picker
                v-model="queryParams.date"
                type="date"
                range-separator="至"
                start-placeholder="发布时间"
                end-placeholder="有效时间">
            </el-date-picker>
        </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-if="opt!== 'details'"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      size="mini"
      height="450"
      :row-style="{ height: '30px' }"
      border
      :cell-style="{ padding: '0px' }"
      :data="fundingList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        label="序号"
        type="index"
        width="50"
        align="center"
        prop="index"
        :index="indexMethod"
      ></el-table-column>
      <el-table-column
        label="资质名称"
        align="center"
        prop="name"
        :show-overflow-tooltip="true"
        width="220"
      />
      <el-table-column
        label="资质类别"
        align="center"
        prop="qualificationType"
        width="140"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.project_funding_type"
            :value="scope.row.qualificationType"
          />
        </template>
      </el-table-column>
      <el-table-column label="资质级别" align="center" prop="level" width="140">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.project_funding_level"
            :value="scope.row.level"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="发布单位"
        align="center"
        prop="publishingUnit"
        :show-overflow-tooltip="true"
        width="220"
      />
      <el-table-column
        label="发布日期"
        align="center"
        prop="releaseDate"
        width="140"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.releaseDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="有效期至"
        align="center"
        prop="validityDate"
        width="140"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.validityDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        v-if="opt!== 'details'"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            title="编辑"
          ></el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            title="删除"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目资金管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-form-item label="资金名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入资金名称" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="资质类别" prop="qualificationType">
              <el-select
                v-model="form.qualificationType"
                placeholder="请选择资质类别"
                style="width: 280px"
              >
                <el-option
                  v-for="dict in dict.type.project_funding_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资质级别" prop="level">
              <el-select
                v-model="form.level"
                placeholder="请选择资质级别"
                style="width: 280px"
              >
                <el-option
                  v-for="dict in dict.type.project_funding_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发布单位" prop="publishingUnit">
              <el-input
                v-model="form.publishingUnit"
                placeholder="请输入发布单位"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布日期" prop="releaseDate">
              <el-date-picker
                clearable
                :disabled="opt == 'details'"
                style="width: 280px"
                v-model="form.releaseDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择发布日期"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="有效期" prop="validityDate">
              <el-date-picker
                clearable
                :disabled="opt == 'details'"
                style="width: 280px"
                v-model="form.validityDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择有效期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所获奖励" prop="rewardsReceived">
              <el-input
                v-model="form.rewardsReceived"
                placeholder="请输入所获奖励"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="来源" prop="source">
            <el-input
              v-model="form.source"
              type="textarea"
              placeholder="请输入来源"
              :autosize="{ minRows: 3, maxRows: 4 }"
              maxlength="5000"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="附件">
            <file-view
              :type="fjFileType"
              :businessId="businessId"
              :businessCode="businessCode"
              @change="getFile"
              :key="refreshKey"
            ></file-view>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listFunding,
  getFunding,
  delFunding,
  addFunding,
  updateFunding,
} from "@/api/project/funding";
import FileView from "@/components/FileView/index";
import pdf from "vue-pdf";
export default {
  name: "Funding",
  dicts: ["project_funding_type", "project_funding_level"],
  components: { FileView, pdf },
  props: {
    enterpriseId: {
      type: String,
      default: null,
    },
    enterpriseName: {
      type: String,
      default: null,
    },
    isEnterprise: {
      type: Boolean,
      default: true,
    },
    opt:{
      type:String,
      default:''
    }
  },
  data() {
    return {
      refreshKey: 0,
      //附件参数
      fjFileType: 0,
      businessId: "",
      opt:"",
      businessCode: "projectFunding",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目资金管理表格数据
      fundingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        name: null,
        qualificationType: null,
        level: null,
        publishingUnit: null,
        releaseDate: null,
        validityDate: null,
        date: [],
        source: null,
        enterpriseId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "资金名称不能为空", trigger: "change" },
          { max: 50, message: "名称长度不能超过50", trigger: "change" },
        ],
        qualificationType: [
          { required: true, message: "资质类别不能为空", trigger: "change" },
        ],
        level: [
          { required: true, message: "资质级别不能为空", trigger: "change" },
        ],
        publishingUnit: [
          { required: true, message: "发布单位不能为空", trigger: "change" },
          { max: 50, message: "发布单位长度不能超过50", trigger: "change" },
        ],
        releaseDate: [
          { required: true, message: "发布日期不能为空", trigger: "change" },
        ],
        validityDate: [
          { required: true, message: "有效期不能为空", trigger: "change" },
        ],
        rewardsReceived: [
          { required: true, message: "所获奖励不能为空", trigger: "change" },
          {
            pattern: /^[0-9]+(\.[0-9]{1,2})?$/,
            message: "请输入正确的奖励金额",
            trigger: "blur",
          },
        ],
      },
      //选当前时间和之前的时间
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      disabledDate: time => {
        const day32 = 32 * 24 * 3600 * 1000;
        if (this.pickerMinDate !== "") {
          let maxTime = this.pickerMinDate + day32;
          if (maxTime > new Date()) {
            maxTime = new Date();
          }
          return (
            time.getTime() > maxTime || time.getTime() > Date.now() - 86400000
          );
        }
        if (this.pickerMaxDate !== "" && !this.pickerMinDate) {
          let minTime = this.pickerMaxDate - day32;
          return (
            time.getTime() < minTime || time.getTime() > Date.now() - 86400000
          );
        }
        return time.getTime() > Date.now() - 86400000;
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getFile(data) {
      //console.log(JSON.stringify(data))
    },
    indexMethod(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },
    /** 查询项目资金管理列表 */
    getList() {
      this.loading = true;
      // if(this.queryParams.date.length==2){
      //     this.queryParams.releaseDate=this.queryParams.date[0]
      //     this.queryParams.validityDate=this.queryParams.date[1]
      // }
      if (this.enterpriseId != null) {
        this.queryParams.enterpriseId = this.enterpriseId;
      }
      listFunding(this.queryParams).then(response => {
        this.fundingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.getList();
    },
    // 表单重置
    reset() {
      this.form = {
        fundId: null,
        name: null,
        qualificationType: null,
        level: null,
        publishingUnit: null,
        releaseDate: null,
        validityDate: null,
        source: null,
        creationTime: null,
        operateTime: null,
        operateId: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        delFlag: null,
        enterpriseId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fundId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    guid() {
      function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
      }
      return (
        S4() +
        S4() +
        "-" +
        S4() +
        "-" +
        S4() +
        "-" +
        S4() +
        "-" +
        S4() +
        S4() +
        S4()
      );
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.refreshKey++;
      this.fjFileType = 0;
      this.businessId = this.guid();
      if (this.enterpriseId != null) {
        this.form.enterpriseId = this.enterpriseId;
      }
      this.open = true;
      this.title = "添加项目资金";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.refreshKey++;
      this.fjFileType = 1;
      const fundId = row.fundId || this.ids;
      this.businessId = row.fundId;
      getFunding(fundId).then(response => {
        // let data=response.data
        // data.date=[response.data.releaseDate,response.data.validityDate]
        this.form = response.data;
        this.open = true;
        this.title = "修改项目资金";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // this.form.releaseDate=this.form.date[0]
          // this.form.validityDate=this.form.date[1]
          //this.form.enterpriseId=this.enterpriseId
          if (this.form.fundId != null) {
            updateFunding(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.$emit("change");
            });
          } else {
            this.form.fundId = this.businessId;
            addFunding(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.$emit("change");
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fundIds = row.fundId || this.ids;
      this.$modal
        .confirm('是否确认删除资金名称为"' + row.name + '"的数据项？')
        .then(function () {
          return delFunding(fundIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "project/funding/export",
        {
          ...this.queryParams,
        },
        `funding_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped lang="scss">
.project-funding-container {
  overflow-y: auto;
  overflow-x: auto;
  padding: 16px;
  max-width: 100%;
  max-height: 90vh;
  box-sizing: border-box;
}

// ... existing styles ...
</style>
